package com.yan.club.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.yan.club.auth.model.AuthUser;
import com.yan.club.auth.model.LoginUser;
import com.yan.club.exception.ServiceException;
import com.yan.club.result.Result;
import com.yan.club.sys.dto.LoginDto;
import com.yan.club.sys.mapper.SysRoleMapper;
import com.yan.club.sys.mapper.SysUserMapper;
import com.yan.club.sys.mapper.SysUserRoleMapper;
import com.yan.club.sys.model.SysRole;
import com.yan.club.sys.model.SysUser;
import com.yan.club.sys.model.SysUserRole;
import com.yan.club.sys.model.SysUserRoleExample;
import com.yan.club.sys.service.SysUserService;
import com.yan.club.sys.vo.LoginUserVo;
import com.yan.club.sys.vo.SysUserExcel;
import com.yan.club.utils.ExcelUtils;
import com.yan.club.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yan.club.auth.constant.RedisConstant.LOGIN_KEY;
import static com.yan.club.auth.utils.SecurityUtil.getUserId;
import static com.yan.club.auth.utils.SecurityUtil.isAdmin;
import static com.yan.club.result.ResultCode.INTERNAL_SERVER_ERROR;

/**
 * @author 彦
 * @since 2024/1/19 15:01
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public Result<LoginUserVo> login(LoginDto loginDto) {

        if (StringUtils.isEmpty(loginDto.getUsername()) || StringUtils.isEmpty(loginDto.getPassword())) {
            return Result.error(INTERNAL_SERVER_ERROR.code, "用户名或者密码为空！");
        }

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 判断是否认证通过
        if (ObjectUtils.isEmpty(authenticate)) {
            return Result.error(INTERNAL_SERVER_ERROR.code, "用户名或密码错误");
        }

        // 生成JWT
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        String token = JwtUtil.createJWT(userId);

        stringRedisTemplate.opsForValue().set(LOGIN_KEY + userId,
                JSON.toJSONString(loginUser), 60, TimeUnit.MINUTES);

        LoginUserVo loginVo = new LoginUserVo();
        BeanUtils.copyProperties(loginUser.getUser(), loginVo);
        loginVo.setToken(token);

        return Result.success(loginVo);

    }

    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public Result<String> logout() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // token过期的情况
        if (authentication == null) {
            return Result.success();
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        AuthUser user = loginUser.getUser();

        // 删除redis中的用户信息 （去除登录状态）
        stringRedisTemplate.delete(LOGIN_KEY + user.getUserId());

        return Result.success();
    }

    /**
     * 根据用户id查询权限信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> selectPermsByUserId(Long userId) {

        List<String> perms;

        // 如果是超级管理员，返回所有权限
        if (isAdmin(userId)) {
            perms = sysUserMapper.selectAllPerms();
        } else {
            perms = sysUserMapper.selectPermsByUserId(userId);
        }

        return perms;
    }

    /**
     * 根据用户id查询角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> selectRoleKeyByUserId(Long userId) {

        List<String> roleKeys = new ArrayList<>();

        // 如果是超级管理员
        if (isAdmin(userId)) {
            roleKeys.add("admin");
        } else {
            roleKeys = sysUserMapper.selectRoleKeyByUserId(userId);
        }

        return roleKeys;
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return sysUserMapper.selectUserList(user);
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!isAdmin(getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return sysUserMapper.selectUserById(userId);
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        long userId = user.getUserId() == null ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkUserNameUnique(user.getUserName());
        return info != null && !info.getUserId().equals(userId);
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        long userId = user.getUserId() == null ? -1L : user.getUserId();

        if (user.getPhonenumber().equals(sysUserMapper.selectByPrimaryKey(userId).getPhonenumber())) {
            return false;
        }

        SysUser info = sysUserMapper.checkPhoneUnique(user.getPhonenumber());
        return info != null && !info.getUserId().equals(userId);
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        long userId = user.getUserId() == null ? -1L : user.getUserId();

        if (user.getEmail().equals(sysUserMapper.selectByPrimaryKey(userId).getEmail())) {
            return false;
        }

        SysUser info = sysUserMapper.checkEmailUnique(user.getEmail());
        return info != null && !info.getUserId().equals(userId);
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> insertUser(SysUser user) {
        // 新增用户信息
        int rows = sysUserMapper.insertUser(user);
        // 新增用户岗位关联
//        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return Result.success();
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (!StringUtils.isEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (!CollectionUtils.isEmpty(list)) {
                sysUserRoleMapper.batchInsert(list);
            }
        }
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (user.getUserId() != null && isAdmin(user.getUserId())) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        SysUserRoleExample example = new SysUserRoleExample();
        example.createCriteria().andUserIdEqualTo(userId);
        sysUserRoleMapper.deleteByExample(example);
        // 新增用户与角色管理
        insertUserRole(user);

        sysUserMapper.updateUser(user);
        return Result.success();
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        sysUserRoleMapper.deleteUserRole(userIds);
        sysUserMapper.deleteUserByIds(userIds);

        return Result.success();
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public Result<String> updateUserStatus(SysUser user) {
        sysUserMapper.updateUser(user);
        return Result.success();
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        SysUserRoleExample ex = new SysUserRoleExample();
        ex.createCriteria().andUserIdEqualTo(userId);
        sysUserRoleMapper.deleteByExample(ex);

        insertUserRole(userId, roleIds);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectAllocatedList(SysUser user) {
        return sysUserMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return sysUserMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return sysUserMapper.selectUserByUserName(userName);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = sysRoleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return "";
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return sysUserMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return sysUserMapper.resetUserPwd(userName, password);
    }

    @Override
    public Result<String> importData(MultipartFile file) {
        if (null == file) {
            return Result.error(INTERNAL_SERVER_ERROR.code, "the file is null");
        }
        // 文件解析
        List<SysUserExcel> list;
        try {
            list = ExcelUtils.readMultipartFile(file, SysUserExcel.class);

            List<SysUser> finalList = list.stream().map(sysUserExcel -> {
                SysUser sysUser = new SysUser();
                BeanUtils.copyProperties(sysUserExcel, sysUser);

                sysUser.setCreateTime(new Date());
                sysUser.setUpdateTime(new Date());
                sysUser.setDelFlag("0");
                sysUser.setStatus("0");
                return sysUser;
            }).collect(Collectors.toList());

            sysUserMapper.batchInsert(finalList);

        } catch (Exception e) {
            return Result.error(INTERNAL_SERVER_ERROR.code, e.getMessage());
        }
        return Result.success();
    }

    @Override
    public void export(HttpServletResponse response, List<SysUser> list) {
        ExcelUtils.export(response, "用户列表", list, SysUserExcel.class);

    }
}
